package myta.service;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;

import myta.bean.Message;
import myta.bean.Session;

public class Utility {
	
	public static void checkAuth() throws Exception{
		ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
		Session admin = (Session)getBean("sessionBean");
		
		if(admin.getIdadmin() == null || admin.getIdadmin().equalsIgnoreCase("")){
			ec.redirect("loginadmin.jsf");
		}
	}
	
	public static String getReportsPath(){
		return getResourcePath() + "reports/";
	}
	
	private static String getResourcePath(){
		ServletContext ctx = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
		return ctx.getRealPath("/resources/") + "/";
	}
	
	public static String format(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		return sdf.format(date);
	}
	
	public static Object getBean(String beanName){
		FacesContext context = FacesContext.getCurrentInstance();
		return context.getApplication().evaluateExpressionGet(context, "#{" + beanName + "}", Object.class);
	}
	
	public static void showMessage(String message){
		Message bean = (Message) getBean("message");
		bean.setMessage("<script>window.alert('"+message+"');</script>");
		bean.setShow(false);
	}
	
	public static boolean isNew() {
		Session bean = (Session) getBean("sessionBean");
		return bean.isNew();
	}

	public static void setNew(boolean isNew) {
		Session bean = (Session) getBean("sessionBean");
		bean.setNew(isNew);
	}
}
